package cn.edu.njuit.springbootdemo.http;

import cn.edu.njuit.springbootdemo.javabean.Article;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ResponseToXlsConverter extends AbstractHttpMessageConverter<Article> {

    // 常量
    private static final MediaType EXCEL_TYPE = MediaType.valueOf(
            "application/vnd.ms-excel");

    //构造方法
    ResponseToXlsConverter() {
        super(EXCEL_TYPE);
    }

    @Override
    protected Article readInternal(final Class<? extends Article> clazz,
                 final HttpInputMessage inputMessage) throws IOException,
            HttpMessageNotReadableException {
        return null;
    }

    //针对AjaxResponse类型返回值，使⽤下⾯的writeInternal⽅法进⾏消息类型转换
    @Override
    protected boolean supports(final Class<?> clazz) {
        return (Article.class == clazz);
    }

    @Override
    protected void writeInternal(final Article article,
                                 final HttpOutputMessage outputMessage) throws IOException,
            HttpMessageNotWritableException {
        //poi操作
        final Workbook workbook = new HSSFWorkbook();
        final Sheet sheet = workbook.createSheet();
        final Row row = sheet.createRow(0);
        row.createCell(0).setCellValue(article.getId());
        row.createCell(1).setCellValue(article.getTitle());
        workbook.write(outputMessage.getBody());
    }
}
